package com.padgett.resourcemanagement;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.padgett.resourcemanagement.data.ClientDAO;
import com.padgett.resourcemanagement.util.SystemConstants;
/**
 * This is to initalize everything including detecting current user.
 * @author andyleung
 *
 */
@SuppressWarnings("serial")
public class InitServlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		execute(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		execute(req,resp);
	}
	/**
	 * Determine if current user is admin, if yes, it will delegate to admin index.
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	private void execute(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		UserService userService=UserServiceFactory.getUserService();
		User user=userService.getCurrentUser();
		Key userKey=new KeyFactory.Builder("User",user.getEmail()).getKey();
		Entity entity=ClientDAO.loadEntity(userKey);
		String page=SystemConstants.ADMIN_INDEX_PAGE;
		if(((String)entity.getProperty("Role")).equalsIgnoreCase("user")){
			page=SystemConstants.USER_INDEX_PAGE;
		}
		RequestDispatcher dispatcher=req.getRequestDispatcher(page);
		dispatcher.forward(req, resp);
	}
	
	@Override
	public void init(ServletConfig config) throws ServletException {
	}
	
}
